package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.ProductMapper;
import com.example.dao.UserMapper;
import com.example.dao.UserOwnMapper;
import com.example.enums.Message;
import com.example.model.Product;
import com.example.model.Result;
import com.example.model.UserOwn;
import com.example.modelDTO.UserOwnDTO;
import com.example.modelDTO.converter.UserOwnConverter;
import com.example.service.IUserOwnService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserOwnServiceImpl extends ServiceImpl<UserOwnMapper, UserOwn> implements IUserOwnService {
    @Autowired
    UserOwnMapper userOwnMapper;

    @Autowired
    UserMapper userMapper;

    @Resource
    ProductMapper productMapper;

    private static final DateTimeFormatter DATE_TIME_FORMATTER=DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Transactional
    public Result<Integer> createUserOwn(Integer productId,Integer userId){
        Product product=productMapper.selectById(productId);
        try {
            int ownedPoints=userMapper.selectById(userId).getUserPoints();
            int costPoints=product.getProductPoints();
            int validityPeriod=product.getValidityPeriod();
            if(ownedPoints<costPoints){
                return Result.fail(false, Message.POINTS_NOT_ENOUGH);
            }
            UserOwn userOwn=new UserOwn();
            LocalDateTime current=LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime expirationDate=current.plusDays(validityPeriod);
            String obtainDateStr=current.format(dateTimeFormatter);
            String expirationDateStr=expirationDate.format(dateTimeFormatter);


            userOwn.setProductId(product.getProductId());
            userOwn.setObtainedTime(obtainDateStr);
            userOwn.setValidityPeriod(validityPeriod);
            userOwn.setExpirationDate(expirationDateStr);
            userOwn.setUserId(userId);
            userOwn.setProductName(product.getProductName());
            userOwn.setProductImage(product.getProductImage());
            userOwn.setCancelled(false);
            userOwnMapper.insert(userOwn);
            userMapper.deductPoints(userId,costPoints);

        }catch (Exception e){
            return Result.fail(userMapper.selectById(userId).getUserPoints());
        }
        return Result.success(userMapper.selectById(userId).getUserPoints());
    }

    public List<UserOwnDTO> getByUserId(int userId){
        return userOwnMapper.getByUserId(userId).stream()
                .filter(this::isNotExpired)
                .map(UserOwnConverter::toDto)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean updateByUserOwnId(Integer userOwnId) {
        UpdateWrapper<UserOwn> userOwnUpdateWrapper = new UpdateWrapper<>();
        userOwnUpdateWrapper.eq("user_own_id",userOwnId).set("cancelled",1);
        return userOwnMapper.update(userOwnUpdateWrapper) == 1 ? true : false;
    }

    private boolean isNotExpired(UserOwn userOwn){
        try{
            LocalDate date= LocalDate.parse(userOwn.getExpirationDate(),DATE_TIME_FORMATTER);
            if(date.isAfter(LocalDate.now())){
                return true;
            }
        }catch (DateTimeParseException e){
            System.out.println("日期格式错误");
            return false;
        }
        return false;
    }
}
